﻿
Imports osi.root.constants
Imports osi.root.formation
Imports osi.root.connector
Imports osi.root.procedure
Imports osi.root.utils

Public Class singleton_device_pool(Of T)
    Inherits device_pool(Of T)
    Implements isync_device_pool(Of T)

    Private ReadOnly d As T

    Public Sub New(ByVal d As T,
                   ByVal identity As String,
                   Optional ByVal validator As Func(Of T, Boolean) = Nothing,
                   Optional ByVal closer As Action(Of T) = Nothing,
                   Optional ByVal device_id As Func(Of T, String) = Nothing)
        MyBase.New(identity, Nothing, validator, closer, device_id)
        assert(Not d Is Nothing)
        Me.d = d
        assert(increase_total_count())
    End Sub

    Public Sub New(ByVal d As T,
                   Optional ByVal validator As Func(Of T, Boolean) = Nothing,
                   Optional ByVal closer As Action(Of T) = Nothing,
                   Optional ByVal device_id As Func(Of T, String) = Nothing)
        Me.New(d, assert_return(Not d Is Nothing, d).GetType().Name(), validator, closer, device_id)
    End Sub

    Protected NotOverridable Overrides Function get_free_count() As UInt32
        If is_valid_device(d) Then
            Return uint32_1
        Else
            zero_total_count()
            Return uint32_0
        End If
    End Function

    Protected NotOverridable Overrides Function create_device(r As pointer(Of T)) As event_comb
        assert(False)
        Return Nothing
    End Function

    Protected NotOverridable Overrides Function get_device(r As pointer(Of T)) As event_comb
        assert(False)
        Return Nothing
    End Function

    Protected NotOverridable Overrides Function sync_get_device(ByRef r As T) As Boolean
        assert(False)
        Return False
    End Function

    Protected NotOverridable Overrides Function release_device(c As T) As Boolean
        assert(False)
        Return False
    End Function

    Protected NotOverridable Overrides Sub close_devices()
        begin_close_device(d)
    End Sub

    Public Shadows Function sync_get(ByRef o As T) As Boolean Implements isync_device_pool(Of T).sync_get
        If Not expired() AndAlso is_valid_device(d) Then
            o = d
            Return True
        Else
            zero_total_count()
            Return False
        End If
    End Function

    Public Shadows Function release(ByVal c As T) As Boolean Implements idevice_pool(Of T).release
        If object_compare(c, d) = 0 AndAlso
           is_valid_device(c) Then
            Return True
        Else
            zero_total_count()
            Return False
        End If
    End Function

    Protected Overrides Sub Finalize()
        MyBase.Finalize()
        GC.KeepAlive(d)
    End Sub
End Class
